"""
学生成绩CSV管理器
使用CSV模块进行数据管理
"""
import csv
import os
import statistics

class GradeManager:
    def __init__(self, filename="grades.csv"):
        self.filename = filename
        self.fieldnames = ['学号', '姓名', '语文', '数学', '英语', '总分', '平均分']
    
    def add_student(self):
        """添加学生成绩"""
        print("\n=== 添加学生成绩 ===")
        
        student_id = input("学号: ")
        name = input("姓名: ")
        
        # 输入各科成绩并验证
        try:
            chinese = float(input("语文成绩: "))
            math = float(input("数学成绩: "))
            english = float(input("英语成绩: "))
            
            if not all(0 <= score <= 100 for score in [chinese, math, english]):
                print("成绩必须在0-100之间！")
                return
            
        except ValueError:
            print("请输入有效的数字！")
            return
        
        # 计算总分和平均分
        total = chinese + math + english
        average = round(total / 3, 2)
        
        student_data = {
            '学号': student_id,
            '姓名': name,
            '语文': chinese,
            '数学': math,
            '英语': english,
            '总分': total,
            '平均分': average
        }
        
        # 检查文件是否存在来决定是否写入表头
        file_exists = os.path.exists(self.filename)
        
        try:
            with open(self.filename, 'a', newline='', encoding='utf-8') as file:
                writer = csv.DictWriter(file, fieldnames=self.fieldnames)
                
                if not file_exists:
                    writer.writeheader()  # 第一次写入表头
                
                writer.writerow(student_data)
            
            print(f"学生 {name} 的成绩已成功添加！")
            
        except IOError as e:
            print(f"文件操作失败: {e}")
    
    def view_all_students(self):
        """查看所有学生成绩"""
        print("\n=== 所有学生成绩 ===")
        
        if not os.path.exists(self.filename):
            print("暂无学生成绩记录")
            return
        
        try:
            with open(self.filename, 'r', newline='', encoding='utf-8') as file:
                reader = csv.DictReader(file)
                
                if not reader.fieldnames:
                    print("文件格式错误")
                    return
                
                # 打印表头
                header = " | ".join(f"{field:^8}" for field in reader.fieldnames)
                print(header)
                print("-" * len(header))
                
                # 打印数据
                for row in reader:
                    data_row = " | ".join(f"{str(row[field]):^8}" for field in reader.fieldnames)
                    print(data_row)
                    
        except Exception as e:
            print(f"读取文件时出错: {e}")
    
    def calculate_statistics(self):
        """计算统计信息"""
        if not os.path.exists(self.filename):
            print("暂无学生成绩记录")
            return
        
        try:
            with open(self.filename, 'r', newline='', encoding='utf-8') as file:
                reader = csv.DictReader(file)
                
                chinese_scores = []
                math_scores = []
                english_scores = []
                total_scores = []
                
                for row in reader:
                    chinese_scores.append(float(row['语文']))
                    math_scores.append(float(row['数学']))
                    english_scores.append(float(row['英语']))
                    total_scores.append(float(row['总分']))
                
                if chinese_scores:
                    print("\n=== 成绩统计 ===")
                    print(f"语文平均分: {statistics.mean(chinese_scores):.2f}")
                    print(f"数学平均分: {statistics.mean(math_scores):.2f}")
                    print(f"英语平均分: {statistics.mean(english_scores):.2f}")
                    print(f"总分最高分: {max(total_scores)}")
                    print(f"总分最低分: {min(total_scores)}")
                    
        except Exception as e:
            print(f"统计计算时出错: {e}")

def main():
    manager = GradeManager()
     
    while True:
        print("\n=== 学生成绩管理系统 ===")
        print("1. 添加学生成绩")
        print("2. 查看所有成绩")
        print("3. 成绩统计")
        print("4. 退出")
        
        choice = input("请选择操作 (1-4): ")
        
        if choice == '1':
            manager.add_student()
        elif choice == '2':
            manager.view_all_students()
        elif choice == '3':
            manager.calculate_statistics()
        elif choice == '4':
            print("感谢使用成绩管理系统！")
            break
        else:
            print("无效选择，请重新输入！")

if __name__ == "__main__":
    main()